package cn.yuhao.party.bar.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.itcast.jdbc.TxQueryRunner;
import cn.yuhao.party.bar.domain.Bar;
import cn.yuhao.party.pager.PageBean;
import cn.yuhao.party.pager.PageConstants;

public class BarInDao {
	private QueryRunner qr = new TxQueryRunner();

	public PageBean<Bar> findAll(int pc) {
		int ps = 10;// 每页记录数
		String sql = "select * from inlist limit ?,?";
		try {
			String sql1 = "select count(*) from inlist";
			Number number = (Number) qr.query(sql1, new ScalarHandler());
			int tr = number.intValue();// 得到了总记录数
			List<Bar> listBar = qr.query(sql, new BeanListHandler<Bar>(
					Bar.class), (pc - 1) * ps, ps);
			PageBean<Bar> pb = new PageBean<Bar>();
			/*
			 * 其中PageBean没有url，这个任务由Servlet完成
			 */
			pb.setBeanList(listBar);
			pb.setPc(pc);
			pb.setPs(ps);
			pb.setTr(tr);

			return pb;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public Bar findById(String id) {
		String sql = "select * from inlist where id=?";

		try {
			Bar Bar = (Bar) qr.query(sql, new BeanHandler<Bar>(Bar.class), id);
			return Bar;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void addBar(Bar Bar) {
		String sql = "insert into inlist values(?,?,?)";
		Object[] params = { Bar.getName(), Bar.getNumber(), Bar.getId() };
		try {
			qr.update(sql, params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void delete(String id) {
		String sql = "delete from inlist where id=?";
		try {
			qr.update(sql, id);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void editBar(Bar Bar) {
		String sql = "update inlist set name=?, number=? where id=?";
		Object[] params = { Bar.getName(), Bar.getNumber(), Bar.getId() };
		try {
			qr.update(sql, params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
}
